package cn.yunxiang.summer.system.service.impl;

import cn.yunxiang.summer.framework.exception.ServiceException;
import cn.yunxiang.summer.system.service.ISysVersionService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import cn.yunxiang.summer.system.domain.po.SysVersion;
import cn.yunxiang.summer.system.domain.bo.SysVersionBo;
import cn.yunxiang.summer.system.domain.vo.SysVersionVo;
import cn.yunxiang.summer.system.mapper.SysVerisonMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@RequiredArgsConstructor
@Service
public class SysVersionServiceImpl extends ServiceImpl<SysVerisonMapper, SysVersion> implements ISysVersionService {

    private final SysVerisonMapper sysVerisonMapper;

    @Override
    public IPage<SysVersionVo> getList(Page<SysVersion> page, SysVersionBo query) {
        return sysVerisonMapper.getList(page,query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysVersion updateStatus(Long id, Integer status) {
        // 查询当前版本
        SysVersion sysVersion = sysVerisonMapper.selectById(id);
        if (sysVersion == null) {
            throw new ServiceException("版本不存在");
        }

        if (status == 1) {
            // 禁用同平台其他所有版本
            sysVerisonMapper.disableOtherVersion(sysVersion.getPlatformType(), id);
        }

        //  更新当前版本状态
        sysVersion.setStatus(status);
        sysVerisonMapper.updateById(sysVersion);

        return sysVersion;
    }


    @Override
    public boolean add(SysVersion sysVersion) {
        // 检查是否设置启用状态
        if (sysVersion.getStatus() == 1) {
            // 禁用其他版本
            sysVerisonMapper.disableOtherVersions(sysVersion.getPlatformType());
        }
        return super.save(sysVersion);
    }
}
